<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>轮胎统计报表</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
  <!-- 引入 jQuery 和 jQuery UI 用于自动补全 -->
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.0/themes/smoothness/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    .stat-card {
      transition: transform 0.2s;
    }
    .stat-card:hover {
      transform: translateY(-5px);
    }
    .brand-table th {
      background-color: #f8f9fa;
    }
    .loading-spinner {
      display: none;
    }
    /* 自动补全样式 */
    .ui-autocomplete {
      max-height: 200px;
      overflow-y: auto;
      overflow-x: hidden;
      z-index: 1000;
    }
    .ui-autocomplete-loading {
      background: white url('https://code.jquery.com/ui/1.13.0/themes/smoothness/images/ui-anim_basic_16x16.gif') right center no-repeat;
      background-size: 16px 16px;
    }
  </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <div class="container">
    <a class="navbar-brand" href="/api/tires">轮胎管理系统</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav me-auto">
        <li class="nav-item">
          <a class="nav-link" href="/api/tires">轮胎列表</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/batch-add">批量添加轮胎</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/usage">查询使用记录</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/visualization/">轮胎可视化</a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" href="/api/tires/statistics">轮胎统计</a>
        </li>
      </ul>
    </div>
  </div>
</nav>

<div class="container mt-4">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <h1>轮胎统计报表</h1>
    <a href="/api/tires" class="btn btn-secondary">返回列表</a>
  </div>

  <!-- 筛选条件 -->
  <div class="card mb-4">
    <div class="card-header">
      <h5 class="mb-0">筛选条件</h5>
    </div>
    <div class="card-body">
      <form id="filterForm" class="row g-3">
        <div class="col-md-3">
          <label for="transportCompany" class="form-label">运输公司</label>
          <select class="form-select" id="transportCompany" name="transportCompany">
            <option value="">全部公司</option>

          </select>
        </div>
        <!-- 新增车牌号筛选条件 -->
        <div class="col-md-3">
          <label for="vehiclePlateNumber" class="form-label">牵引车牌号</label>
          <input type="text" class="form-control" id="vehiclePlateNumber" name="vehiclePlateNumber"
                 placeholder="输入车头牌号，支持自动补全">
        </div>
        <div class="col-md-3">
          <label for="trailerPlateNumber" class="form-label">挂车牌号</label>
          <input type="text" class="form-control" id="trailerPlateNumber" name="trailerPlateNumber"
                 placeholder="输入车尾牌号，支持自动补全">
        </div>
        <div class="col-md-3">
          <label for="startDate" class="form-label">开始日期</label>
          <input type="date" class="form-control" id="startDate" name="startDate">
        </div>
        <div class="col-md-3">
          <label for="endDate" class="form-label">结束日期</label>
          <input type="date" class="form-control" id="endDate" name="endDate">
        </div>
        <div class="col-md-12">
          <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary">查询</button>
            <button type="button" id="resetBtn" class="btn btn-secondary">重置</button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- 加载提示 -->
  <div id="loadingSpinner" class="loading-spinner text-center mb-4">
    <div class="spinner-border text-primary" role="status">
      <span class="visually-hidden">加载中...</span>
    </div>
    <p class="mt-2">正在加载数据...</p>
  </div>

  <!-- 总体统计卡片 -->
  <div id="statisticsCards" class="row mb-4" style="display: none;">
    <div class="col-md-3 mb-3">
      <div class="card text-white bg-primary stat-card">
        <div class="card-body">
          <h5 class="card-title">总轮胎数</h5>
          <p class="card-text display-6" id="totalTires">0</p>
        </div>
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <div class="card text-white bg-success stat-card">
        <div class="card-body">
          <h5 class="card-title">轮胎总价值</h5>
          <p class="card-text display-6" id="totalTireValue">¥0</p>
        </div>
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <div class="card text-white bg-info stat-card">
        <div class="card-body">
          <h5 class="card-title">装胎总费用</h5>
          <p class="card-text display-6" id="totalInstallCost">¥0</p>
        </div>
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <div class="card text-white bg-warning stat-card">
        <div class="card-body">
          <h5 class="card-title">维修调胎费用</h5>
          <p class="card-text display-6" id="totalRepairSwapCost">¥0</p>
        </div>
      </div>
    </div>
  </div>

  <!-- 图表区域 -->
  <div class="row mb-4">
    <div class="col-md-6">
      <div class="card">
        <div class="card-header">
          <h5 class="mb-0">轮胎状态分布</h5>
        </div>
        <div class="card-body">
          <canvas id="statusChart" width="400" height="300"></canvas>
        </div>
      </div>
    </div>
    <div class="col-md-6">
      <div class="card">
        <div class="card-header">
          <h5 class="mb-0">费用构成</h5>
        </div>
        <div class="card-body">
          <canvas id="costChart" width="400" height="300"></canvas>
        </div>
      </div>
    </div>
  </div>

  <!-- 品牌型号统计表格 -->
  <div class="card">
    <div class="card-header">
      <h5 class="mb-0">按品牌型号统计</h5>
    </div>
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-striped brand-table">
          <thead>
          <tr>
            <th>品牌型号</th>
            <th>数量</th>
            <th>平均单价</th>
            <th>总价值</th>
            <th>使用中</th>
            <th>已报废</th>
          </tr>
          </thead>
          <tbody id="brandStatsBody">
          <!-- 数据将通过JavaScript动态填充 -->
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<footer class="bg-dark text-white mt-5 py-4">
  <div class="container text-center">
    <p class="mb-0">轮胎管理系统 &copy; 2025</p>
  </div>
</footer>

<script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script>
  // 动态加载运输公司列表
  function loadTransportCompanies() {
    return fetch('/api/tires/transport-companies')
            .then(response => {
              if (!response.ok) {
                throw new Error('网络响应不正常');
              }
              return response.json();
            })
            .then(companies => {
              const companySelect = document.getElementById('transportCompany');

              // 清空现有选项（除了"全部公司"选项）
              while (companySelect.options.length > 1) {
                companySelect.remove(1);
              }

              // 添加新的运输公司选项
              companies.forEach(company => {
                const option = document.createElement('option');
                option.value = company;
                option.textContent = company;
                companySelect.appendChild(option);
              });

              console.log('加载运输公司列表成功，数量:', companies.length);
            })
            .catch(error => {
              console.error('加载运输公司列表失败:', error);
              // 显示错误信息
              alert('加载运输公司列表失败: ' + error.message);
            });
  }

  // 页面加载完成后执行
  document.addEventListener('DOMContentLoaded', function() {
    // 设置默认日期为今年
    const currentYear = new Date().getFullYear();
    document.getElementById('startDate').value = currentYear + '-01-01';
    document.getElementById('endDate').value = currentYear + '-12-31';

    // 先加载运输公司，再加载统计数据
    loadTransportCompanies().then(() => {
      loadStatistics();
    }).catch(error => {
      console.error('初始化失败:', error);
      // 即使运输公司加载失败，也尝试加载统计数据
      loadStatistics();
    });

    // 表单提交事件
    document.getElementById('filterForm').addEventListener('submit', function(e) {
      e.preventDefault();
      loadStatistics();
    });

    // 重置按钮事件
    document.getElementById('resetBtn').addEventListener('click', function() {
      document.getElementById('transportCompany').value = '';
      document.getElementById('vehiclePlateNumber').value = '';
      document.getElementById('trailerPlateNumber').value = '';
      document.getElementById('startDate').value = currentYear + '-01-01';
      document.getElementById('endDate').value = currentYear + '-12-31';
      loadStatistics();
    });

    // 初始化自动补全功能
    initializeAutocomplete();
  });

  let statusChart, costChart;

  // 自动补全初始化函数
  function initializeAutocomplete() {
    // 为牵引车牌号输入框添加自动补全功能
    $("#vehiclePlateNumber").autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "/api/tires/autocomplete/plate-numbers",
          dataType: "json",
          data: {
            term: request.term
          },
          beforeSend: function() {
            $("#vehiclePlateNumber").addClass("ui-autocomplete-loading");
          },
          success: function(data) {
            response(data);
          },
          error: function() {
            response([]);
          },
          complete: function() {
            $("#vehiclePlateNumber").removeClass("ui-autocomplete-loading");
          }
        });
      },
      minLength: 1, // 输入1个字符就开始联想
      delay: 300, // 延迟300毫秒
      select: function(event, ui) {
        // 当用户选择联想项时，自动填充完整的车牌号
        $("#vehiclePlateNumber").val(ui.item.value);
        return false; // 阻止默认行为
      },
      focus: function(event, ui) {
        // 防止在焦点移动时更改输入框的值
        event.preventDefault();
      }
    });

    // 为挂车牌号输入框添加自动补全功能
    $("#trailerPlateNumber").autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "/api/tires/autocomplete/plate-numbers",
          dataType: "json",
          data: {
            term: request.term
          },
          beforeSend: function() {
            $("#trailerPlateNumber").addClass("ui-autocomplete-loading");
          },
          success: function(data) {
            response(data);
          },
          error: function() {
            response([]);
          },
          complete: function() {
            $("#trailerPlateNumber").removeClass("ui-autocomplete-loading");
          }
        });
      },
      minLength: 1, // 输入1个字符就开始联想
      delay: 300, // 延迟300毫秒
      select: function(event, ui) {
        // 当用户选择联想项时，自动填充完整的车牌号
        $("#trailerPlateNumber").val(ui.item.value);
        return false; // 阻止默认行为
      },
      focus: function(event, ui) {
        // 防止在焦点移动时更改输入框的值
        event.preventDefault();
      }
    });

    // 输入框获得焦点时自动选择所有文本，方便用户重新输入
    $("#vehiclePlateNumber, #trailerPlateNumber").focus(function() {
      $(this).select();
    });
  }

  function loadStatistics() {
    const loadingSpinner = document.getElementById('loadingSpinner');
    const statisticsCards = document.getElementById('statisticsCards');

    // 显示加载提示，隐藏统计卡片
    loadingSpinner.style.display = 'block';
    statisticsCards.style.display = 'none';

    // 获取筛选条件
    const transportCompany = document.getElementById('transportCompany').value;
    const vehiclePlateNumber = document.getElementById('vehiclePlateNumber').value;
    const trailerPlateNumber = document.getElementById('trailerPlateNumber').value;
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;

    // 构建查询参数
    const params = new URLSearchParams();
    if (transportCompany) params.append('transportCompany', transportCompany);
    if (vehiclePlateNumber) params.append('vehiclePlateNumber', vehiclePlateNumber);
    if (trailerPlateNumber) params.append('trailerPlateNumber', trailerPlateNumber);
    if (startDate) params.append('startDate', startDate);
    if (endDate) params.append('endDate', endDate);

    // 同时获取总体统计和品牌统计
    Promise.all([
      fetch(`/api/tires/statistics/data?${params}`).then(r => r.json()),
      fetch(`/api/tires/statistics/by-brand?${params}`).then(r => r.json())
    ]).then(([statistics, brandStats]) => {
      // 更新总体统计卡片
      updateStatisticsCards(statistics);

      // 更新品牌统计表格
      updateBrandStatsTable(brandStats);

      // 更新图表
      updateCharts(statistics, brandStats);

      // 隐藏加载提示，显示统计卡片
      loadingSpinner.style.display = 'none';
      statisticsCards.style.display = 'flex';
    }).catch(error => {
      console.error('加载统计数据失败:', error);
      loadingSpinner.style.display = 'none';
      alert('加载统计数据失败，请重试');
    });
  }

  function updateStatisticsCards(statistics) {
    document.getElementById('totalTires').textContent = statistics.totalTires || 0;
    document.getElementById('totalTireValue').textContent = '¥' + (statistics.totalTireValue || 0);
    document.getElementById('totalInstallCost').textContent = '¥' + (statistics.totalInstallCost || 0);

    const repairCost = statistics.totalRepairCost || 0;
    const swapCost = statistics.totalSwapCost || 0;
    document.getElementById('totalRepairSwapCost').textContent = '¥' + (repairCost + swapCost);
  }

  function updateBrandStatsTable(brandStats) {
    const tbody = document.getElementById('brandStatsBody');
    tbody.innerHTML = '';

    if (!brandStats || brandStats.length === 0) {
      tbody.innerHTML = '<tr><td colspan="6" class="text-center">暂无数据</td></tr>';
      return;
    }

    brandStats.forEach(item => {
      const row = document.createElement('tr');
      row.innerHTML = `
            <td>${item.brandModel}</td>
            <td>${item.count}</td>
            <td>¥${item.avgPrice || 0}</td>
            <td>¥${item.totalValue || 0}</td>
            <td>${item.activeCount || 0}</td>
            <td>${item.scrappedCount || 0}</td>
        `;
      tbody.appendChild(row);
    });
  }

  function updateCharts(statistics, brandStats) {
    // 销毁旧图表
    if (statusChart) statusChart.destroy();
    if (costChart) costChart.destroy();

    // 轮胎状态分布图
    const statusCtx = document.getElementById('statusChart').getContext('2d');
    statusChart = new Chart(statusCtx, {
      type: 'doughnut',
      data: {
        labels: ['使用中', '已报废', '有修补记录'],
        datasets: [{
          data: [
            statistics.activeTires || 0,
            statistics.scrappedTires || 0,
            statistics.repairedTires || 0
          ],
          backgroundColor: [
            '#28a745',
            '#6c757d',
            '#ffc107'
          ]
        }]
      },
      options: {
        responsive: true,
        plugins: {
          legend: {
            position: 'bottom'
          }
        }
      }
    });

    // 费用构成图
    const costCtx = document.getElementById('costChart').getContext('2d');
    costChart = new Chart(costCtx, {
      type: 'pie',
      data: {
        labels: ['轮胎价值', '装胎费用', '维修费用', '调胎费用'],
        datasets: [{
          data: [
            statistics.totalTireValue || 0,
            statistics.totalInstallCost || 0,
            statistics.totalRepairCost || 0,
            statistics.totalSwapCost || 0
          ],
          backgroundColor: [
            '#007bff',
            '#17a2b8',
            '#ffc107',
            '#fd7e14'
          ]
        }]
      },
      options: {
        responsive: true,
        plugins: {
          legend: {
            position: 'bottom'
          }
        }
      }
    });
  }
</script>
</body>
</html>